package com.yupi.springbootinit.neo4j;

import com.yupi.springbootinit.model.entity.Node;
import org.neo4j.driver.Driver;
import org.neo4j.driver.Result;
import org.neo4j.driver.Session;
import org.neo4j.driver.Transaction;
import org.neo4j.driver.Record;
import org.neo4j.driver.Value;
import org.springframework.stereotype.Repository;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

@Repository
public class NodeRepository {

    private final Driver driver;

    public NodeRepository(Driver driver) {
        this.driver = driver;
    }

    // 1. 查询所有节点，跳过前 500 个，限制返回 180 个
    public List<Node> selectAll() {
        String query = "MATCH p=(n:my_entity) RETURN n SKIP 500 LIMIT 180";
        return runQuery(query);
    }

    // 2. 查询所有节点，不跳过和限制
    public List<Node> selectAllIndex() {
        String query = "MATCH (n:my_entity)\n" +
                "RETURN n, ID(n) AS id\n";
        return runQuery(query);
    }

    // 3. 根据名称查询节点
    public Node findByName(String name) {
        String query = String.format("MATCH (p:my_entity {name: '%s'}) RETURN p", name);
        List<Node> nodes = runQuery(query);
        return nodes.isEmpty() ? null : nodes.get(0);
    }

    // 运行查询并将结果转换为 Node 列表
    private List<Node> runQuery(String query) {
        List<Node> nodes = new ArrayList<>();

        try (Session session = driver.session()) {
            Transaction transaction = session.beginTransaction();
            Result result = transaction.run(query);

            while (result.hasNext()) {
                Record record = result.next();
                Value nodeValue = record.get("n");
                Value id = record.get("id");
                Node node = mapToNode(nodeValue, id);
                nodes.add(node);
            }

            transaction.commit();
        }

        return nodes;
    }

    // 将 Neo4j 的查询结果映射到 Node 对象
    private Node mapToNode(Value nodeValue , Value nodeId) {
        Long id = nodeValue.get("id").isNull() ? nodeId.asLong(): nodeValue.get("id").asLong() ;
        String entity = nodeValue.get("entity").asString();
        String name = nodeValue.get("name").asString();
        return new Node(id, entity, name);
    }



    private Long RandomId( Value nodeValue){
        String entity = nodeValue.get("entity").asString();
        String substring = entity.substring(1, entity.length() - 1);
        return Long.parseLong(substring);
    }
}
